package org.bmi.gwt.examples.servertoclient.server;

import org.apache.log4j.Logger;
import org.bmi.gwt.examples.servertoclient.shared.PrinterObject;
import org.bmi.gwt.mi.server.events.StartupEvent;
import org.bmi.gwt.mi.server.events.StartupEventHandler;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.callbacks.BindCallback;
import org.bmi.gwt.mi.shared.exceptions.MiException;
import org.bmi.gwt.mi.shared.exceptions.NameParseException;
import org.bmi.gwt.mi.shared.exceptions.NotAllowedQueueException;

public class ServerToClientStartup implements StartupEventHandler
{
	static protected Logger logger = Logger.getLogger(ServerToClientStartup.class);

	/*
	 * A the application startup, a queue is created and is bound to an object
	 * by its ID. Since this moment this object within the queue context will be
	 * identified by that ID.
	 */

	@Override
	public void onInitialize(StartupEvent event)
	{
		try
		{
			Channel queue = event.getChannel("org.bmi.gwt.mi.test.s2c.server");
			queue.bind(new BindCallback()
			{
				@Override
				public void onError(MiException error)
				{
					logger.info("[ServerToClientStartup] error while binding the server queue: " + error);
				}

				@Override
				public void onBound(Channel channel)
				{
					channel.register("server_printer_id", new PrinterObject()
					{
						@Override
						public void print(String str)
						{
							logger.info("[" + this.getClass().toString() + ".print(String)] " + str);
						}
					});
				}
			});
		}
		catch (NameParseException e)
		{}
		catch (NotAllowedQueueException e)
		{}
	}
}
